package cn.donting.plugin.spring.boot.starter.dev;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 *  开发环境的启动类
 * @author donting
 *  2020-05-15 下午2:23
 */
@Slf4j

public class DevPluginRun {

    @Getter
    private static Class<?> plugDevClass;
    @Getter
    private static DevPluginClassLoader devPluginClassLoader;


    public static AnnotationConfigApplicationContext run(Class<?> devMainClass, Class<?> mainClass, String[] args, String activeProfiles) throws Exception {
        DevPluginClassLoader devPluginClassLoader = devPluginClassLoader(devMainClass);
        Class<?> aClass = devPluginClassLoader.loadClass(mainClass.getName());
        String[] p = new String[]{"--spring.output.ansi.enabled=always", "--donting.plugin.runMode=dev"};
        String[] argss = new String[args.length + p.length];
        System.arraycopy(args, 0, argss, 0, args.length);
        System.arraycopy(p, 0, argss, args.length, p.length);
        plugDevClass = devMainClass;
        Method method = aClass.getMethod("main", args.getClass());
        method.invoke(null, new Object[]{argss});
        return DevPluginLoader.getPluginDevWrapper();
    }

    public static AnnotationConfigApplicationContext run(Class<?> devMainClass, Class<?> mainClass, String[] args) throws Exception {
        return run(devMainClass, mainClass, args, null);
    }

    private static DevPluginClassLoader devPluginClassLoader(Class<?> devMainClass) {
        URLClassLoader appClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        URL calsses = devMainClass.getResource("/");
        DevPluginClassLoader devPluginClassLoader = new DevPluginClassLoader(calsses, appClassLoader);
        DevPluginRun.devPluginClassLoader = devPluginClassLoader;
        return devPluginClassLoader;
    }
}
